package br.ufc.cloud.service.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionManagerMSJDBC {

	private static Statement st;
	private static Connection con;

	public static PreparedStatement PrepStatement(String query) {
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(query);
		} catch (SQLException e) {
			System.out.println("An error ocurred:" + e.getMessage());
		}
		return ps;
	}

	private static void loadDriver() {

		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			System.out.println("Driver not loaded!");
			e.printStackTrace();
		}

		System.out.println("Driver loaded!");

	}

	public static Statement getStatement() {
		if (st != null) {
			return st;
		} else {
			try {
				st = con.createStatement();
			} catch (SQLException e) {
				System.out.println("An error ocurred:" + e.getMessage());
			}
		}
		return st;
	}

	public static void setDriver() {
		if (con == null) {
			loadDriver();
		}

		try {
			con = DriverManager
					.getConnection("jdbc:sqlserver://nvnkoqcrw5.database.windows.net:1433;database=QNotes;user=witalobenicio@nvnkoqcrw5;password={wb2307****};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("An error ocurred:" + e.getMessage());
		}
	}

	private static void closeConection() {
		try {
			con.close();
		} catch (SQLException e) {
			System.out.println("Houve um erro:" + e.getMessage());
			e.printStackTrace();
		}
	}

}
